//
//  logonViewController.m
//  HQJFacilitator
//
//  Created by mymac on 2016/10/11.
//  Copyright © 2016年 Fujian first time iot technology investment co., LTD. All rights reserved.
//

#import "logonVipViewController.h"
#import "SUCCESSViewController.h"
static NSString * kAlphaNum = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 @／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\"";
@interface logonVipViewController ()<UITextFieldDelegate>
{
    UITextField *_nameTextField;
    UITextField *_idTextField;
    UITextField *_mobileTextField;
}
@property (nonatomic,strong)NSArray *labelTitleAry;
@property (nonatomic,strong)NSArray *textTitleAry;
@property (nonatomic,strong)NSMutableArray *textArray;
@property (nonatomic,strong)NSTimer *clockTimer;
@property (nonatomic,assign)NSInteger seconds;
@property (nonatomic,strong)UITextField *VerificationCodeTextField;
@property (nonatomic,strong)UIButton *logonBtn;
@property (nonatomic,assign)BOOL isOkMobile;   //  -- 手机号是否能用
@property (nonatomic,strong)JKCountDownButton *getCodeBtn;
@end

@implementation logonVipViewController
-(NSArray *)labelTitleAry {
    if (!_labelTitleAry) {
        _labelTitleAry = @[@"姓    名:",@"身份证:",@"电    话:"];
    }
    
    return _labelTitleAry;
}
-(NSArray *)textTitleAry {
    
    if (!_textTitleAry) {
        _textTitleAry = @[@"请输入姓名(2到4个汉字)",@"请输入身份证号码",@"请输入手机号码"];
    }
    
    return _textTitleAry;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.title =@"会员注册";
    // --- 视图内容
    [self createView];
    
    //  --- 信号
    [self createSignal];
}
-(void)createView {
    
    _textArray  = [NSMutableArray array];
    
    for (NSInteger i=0; i<3; i++) {
        UILabel *label = [[UILabel alloc]init];
//        label.backgroundColor = [UIColor redColor];
        label.text = self.labelTitleAry[i];
//        label.tag = i;
        label.frame = CGRectMake(15, i%3*(20+30)+20+64, 60, 20);
        [self.view addSubview:label];
//        [_labelArray addObject:label];
        UITextField *textField = [[UITextField alloc]init];
        textField.tag = i;
        textField.backgroundColor = [UIColor whiteColor];
        textField.placeholder = self.textTitleAry[i];
//        textField.font = [UIFont systemFontOfSize:16];
        textField.frame = CGRectMake(15+60+15,i%3*(35+15)+15+64, WIDTH-15*3-60, 35);
        textField.borderStyle = UITextBorderStyleRoundedRect;
        if (textField.tag == 0) {
            
        }
        switch (textField.tag) {
            case 0:
                _nameTextField = textField;
                textField.keyboardType = UIKeyboardTypeDefault;
                textField.delegate = self;
                break;
            case 1:
                _idTextField = textField;
                textField.keyboardType = UIKeyboardTypeNumberPad;
                break;
            case 2:
                _mobileTextField =textField;
                textField.keyboardType = UIKeyboardTypeNumberPad;
                break;
            default:
                break;
        }
        [self.view addSubview:textField];
        [_textArray addObject:textField];
    }
    
#pragma mark --
#pragma mark --- 验证码输入框
    _VerificationCodeTextField = [[UITextField alloc]init];
    [self.view addSubview:_VerificationCodeTextField];

    _VerificationCodeTextField.backgroundColor = [UIColor whiteColor];
    _VerificationCodeTextField.borderStyle = UITextBorderStyleRoundedRect;
    _VerificationCodeTextField.keyboardType = UIKeyboardTypeNumberPad;

    _VerificationCodeTextField.sd_layout.leftSpaceToView(self.view,15).topSpaceToView(_mobileTextField,15).heightIs(35).widthIs(WIDTH-15*2-5-99.5);
     
    _VerificationCodeTextField.placeholder = @"请输入验证码";
    
#pragma mark --
#pragma mark ---获取验证码按钮
   _getCodeBtn = [JKCountDownButton buttonWithType:UIButtonTypeCustom];
    _getCodeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _getCodeBtn.layer.cornerRadius = 5;
    _getCodeBtn.layer.masksToBounds = YES;
    [_getCodeBtn setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
    [_getCodeBtn countDownButtonHandler:^(JKCountDownButton*sender, NSInteger tag) {
        if (_isOkMobile) {
            
            
            
            [RequestEngine HQJFacilitatorRequestDetailsUrl:[NSString stringWithFormat:@"%@getRegCusSMS/mobile/%@",AppOrg_URL,_mobileTextField.text] complete:^(NSDictionary *dic) {
                HQJLog(@"收到的验证码是:%@",dic);
                
                if ([dic[@"error"]integerValue] == 0) {
                    
                    _getCodeBtn.enabled = NO;
                    
                    [sender startCountDownWithSecond:60];
                    
                    [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton,NSUInteger second) {
                        NSString *title = [NSString stringWithFormat:@"剩余%zd秒",second];
                        return title;
                    }];
                    [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
                        
                        countDownButton.enabled = YES;
                        return @"点击重新获取";
                        
                    }];
                } else {
                    
                }
                
            } andError:^(NSError *error) {
                
            } ShowHUD:NO];
            
            
         
        }
      
        
    }];


    _getCodeBtn.backgroundColor = [ManagerEngine getColor:@"00ccb8"];
    [self.view addSubview:_getCodeBtn];
    _getCodeBtn.sd_layout.leftSpaceToView(_VerificationCodeTextField,5).topEqualToView(_VerificationCodeTextField).heightIs(35).widthIs(99.5);
#pragma mark --
#pragma mark ---注册按钮
    _logonBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_logonBtn bk_addEventHandler:^(id  _Nonnull sender) {
//       
//    } forControlEvents:UIControlEventTouchUpInside];
    _logonBtn.backgroundColor = [ManagerEngine getColor:@"00ccb8"];
    [self.view addSubview:_logonBtn];
    [_logonBtn setTitle:@"注册" forState:UIControlStateNormal];
    _logonBtn.layer.cornerRadius = 5;
    _logonBtn.layer.masksToBounds = YES;
    _logonBtn.sd_layout.leftEqualToView(_VerificationCodeTextField).topSpaceToView(_VerificationCodeTextField,30).heightIs(44).widthIs(WIDTH-15*2);
    

    
    
    
}

-(void)createSignal {
    RACSignal * nameSignal = [_nameTextField.rac_textSignal map:^id(id value) {
        return @([ManagerEngine isNameValid:value]);
    }];

    RACSignal * idSignal = [_idTextField.rac_textSignal map:^id(id value) {
        return @([ManagerEngine validateIdentityCard:value]);
    }];
    RACSignal * mobileSignal = [_mobileTextField.rac_textSignal map:^id(id value) {
        return @([ManagerEngine valiMobile:value]);
    }];
    RACSignal * isCodeSignal = [_VerificationCodeTextField.rac_textSignal map:^id(id value) {
        return @([self invalideString:value]);
    }];
    RAC(_getCodeBtn,backgroundColor) = [mobileSignal map:^id(NSNumber *value) {
        return [value boolValue]?[ManagerEngine getColor:@"00ccb8"]:[ManagerEngine getColor:@"8ae6dc"];
    }];
//    RAC(_getCodeBtn,enabled) = [mobileSignal map:^id(NSNumber *value) {
//        return value ;
//    }];
    RACSignal * upSignal = [RACSignal combineLatest:@[nameSignal,idSignal,mobileSignal,isCodeSignal] reduce:^id(NSNumber *nameValid,NSNumber *idValid,NSNumber *movileValid,NSNumber *codeValid){
        return @([nameValid boolValue]&&[idValid boolValue]&&[movileValid boolValue]&&[codeValid boolValue]);
    }];
    
    [upSignal subscribeNext:^(NSNumber *mergeSignal) {
        _logonBtn.enabled = [mergeSignal boolValue];
        if ([mergeSignal boolValue]) {
            _logonBtn.backgroundColor = [ManagerEngine getColor:@"00ccb8"];
            
        } else {
            _logonBtn.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];
            
        }
    }];
    
    
    RACSignal * upMobileSignal = [RACSignal combineLatest:@[mobileSignal] reduce:^id(NSNumber *movileValid){
        return @([movileValid boolValue]);
    }];
    
    [upMobileSignal subscribeNext:^(NSNumber *mergeSignal) {
        if ([mergeSignal boolValue]) {
            [self mobileIsUsed];

        } 
    }];
    RACSignal * idUpSignal = [RACSignal combineLatest:@[idSignal] reduce:^id(NSNumber *idValid){
        return @([idValid boolValue]);
    }];
    
    [idUpSignal subscribeNext:^(NSNumber *mergeSignal) {
        
        if ([mergeSignal boolValue]) {
            [RequestEngine HQJFacilitatorRequestDetailsUrl:[NSString stringWithFormat:@"%@getRealname/identitynum/%@",AppOrg_URL,_idTextField.text] complete:^(NSDictionary *dic) {
                HQJLog(@"======:%@",dic);
                if([dic[@"error"]integerValue] != 0) {
                    
                 [ManagerEngine homeSvpStr:dic[@"result"][@"errmsg"] andcenterView:self.view andStyle:promptViewDefault];
                }
                
                
            } andError:^(NSError *error) {
                
            } ShowHUD:NO];
            
        } else {
            [ManagerEngine dismissHomeSvP];
        }
    }];
    
    [[_logonBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *btn) {
        
        [self requstLogon];
        
        HQJLog(@"点击了注册");
        
    }];
    
}



#pragma mark --
#pragma mark --- 验证手机号是否注册 
-(void)mobileIsUsed {
    for (UITextField *text in _textArray) {
        if (text.tag == 2) {
            if ([ManagerEngine valiMobile:text.text]){
                [RequestEngine HQJFacilitatorRequestDetailsUrl:[NSString stringWithFormat:@"%@getCusRealname/mobile/%@",AppOrg_URL,text.text] complete:^(NSDictionary *dic) {
                    if ([dic[@"error"]integerValue] == 0) {
                        
                        _isOkMobile = YES;
                    } else {
                        [ManagerEngine homeSvpStr:dic[@"result"][@"errmsg"] andcenterView:self.view andStyle:promptViewDefault];
                        _isOkMobile = NO;
                    }
                } andError:^(NSError *error) {
                    
                } ShowHUD:NO];

            }else {
                [ManagerEngine homeSvpStr:@"请核对手机号后重试" andcenterView:self.view andStyle:promptViewDefault];
                _isOkMobile = NO;
            }
        }
    }

    
    

}
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    if (textField == _nameTextField) {
//        
//      
//        if ([string isEqualToString:@""]) {
//            return YES;
//        } else {
//            if (_nameTextField.text.length<=4) {
//           
////            if ( [string isEqualToString:filtered]) {
////                return NO;
////            } else {
////                return YES;
////            }
//                
//                HQJLog(@"-=-=-=-=:%@",string);
//                return [string isEqualToString:filtered]?NO:YES;
//            } else {
//                return NO;
//            }
//        }
//        
//    }
//    return YES;
//    
//    
//}

-(void)aa {
    
}


#pragma mark --
#pragma mark --- 验证码的判断
-(BOOL)invalideString:(NSString *)text {
    
    if (text.length!= 4) {
        return NO;
    } else {
        
        return YES;
    }
}

#pragma mark --
#pragma mark ---点击注册后请求
-(void)requstLogon{
    NSString *urlStr = [NSString stringWithFormat:@"%@customerAddAction/oid/%@/realname/%@/identitynum/%@/mobile/%@/inputCode/%@",AppOrg_URL,[FileEngine filePathNameReadName:@"memberid" andstye:fileLoginStyle],_nameTextField.text,_idTextField.text,_mobileTextField.text,_VerificationCodeTextField.text];
    HQJLog(@"姓名是：%lu",_nameTextField.text.length);
   
    NSString* encodedString = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [RequestEngine HQJFacilitatorRequestDetailsUrl:encodedString complete:^(NSDictionary *dic) {
//        NSLog(@"");
        HQJLog(@"注册结果%@",dic);
      
        if ([dic[@"error"]integerValue]==0 && [dic[@"result"][@"errmsg"]isEqualToString:@"SUCCESS"]) {
            
            SUCCESSViewController *SVC = [[SUCCESSViewController alloc]init];
            SVC.title = @"会员注册";
            [self.navigationController pushViewController:SVC animated:YES];

            
        } else {
              [ManagerEngine customAlert:dic[@"result"][@"errmsg"] andViewController:self isBack:NO];

        }
    } andError:^(NSError *error) {
        
    } ShowHUD:YES];
    
    
    
}


@end
